import { Component, Vue } from 'vue-property-decorator';
import style from '@/styles/views/log.module.less';
import { EapLayout, Temperature } from '@/components';
import { Calendar, Cell, Empty, Icon, Loading, NavBar, Swipe, SwipeItem } from 'vant';
import { IResponse } from '@/interfaces/common.interface';
import { ILogMessage, IRoom } from '@/interfaces/api.interface';
import _ from 'lodash';
import Utils from '@/common/Utils';

interface ILogInfoResp extends IResponse {
  data: ILogMessage[];
}

Vue.use(Calendar);

@Component({
  components: {
    'eap-layout': EapLayout,
    'van-nav-bar': NavBar,
    'van-cell': Cell,
    'van-icon': Icon,
    'van-swipe': Swipe,
    'van-swipe-item': SwipeItem,
    'van-empty': Empty,
    'van-loading': Loading
  },
  sockets: {
    log(data: { room_id: string; messages: ILogMessage[] }) {
      if (this.$data.room && this.$data.room.id === data.room_id) {
        this.$data.operationLogMessages = data.messages;
      }
    },
    addLog(data: { room_id: string; data: ILogMessage }) {
      if (this.$data.room && this.$data.room.id === data.room_id) {
        this.$data.operationLogMessages.unshift(data.data)
      }
    }
  }
})
export default class LogDetail extends Vue {
  private room: IRoom | null = null;
  private minDate: Date = new Date();
  private operationDate = '2021-08-28';
  private operationLogMessages: ILogMessage[] = []; // 当前选中日期的操作日志信息
  private model = false;
  private touchable = true;
  private init = true;

  public created() {
    this.operationDate = Utils.getCurDateTime().date;
    this.minDate = new Date(+new Date() - 7 * 24 * 60 * 60 * 1000);
    const {
      query: { room_id }
    } = this.$route;
    if (!room_id) {
      this.$message.error('程序出现未知错误,请重试！');
      this.$router.push({ name: 'log' });
      return;
    }
    this.room = _.find(this.$store.state.rooms, { id: room_id });
    if (!this.room) {
      this.$message.error('未找到当前房间信息,请刷新页面重试！');
      this.$router.push({ name: 'log' });
      return;
    }
    setTimeout(() => {
      this.getLogByDate(this.operationDate);
      this.init = false;
    }, 1000);
  }

  public render() {
    return (
      <eap-layout>
        <van-nav-bar title={this.room?.name || '-'} slot='header'>
          <van-icon
            name='arrow-left'
            slot='left'
            color='#fff'
            on-click={() => {
              this.$router.push({ name: 'log' });
            }}
          />
        </van-nav-bar>
        <div class={style['log-detail']}>
          <van-swipe show-indicators={false} loop={false} touchable={this.touchable}>
            <van-swipe-item>
              <div class={style['log-detail-item']}>
                <div class={style['log-detail-title']}>操作日志</div>
                <div
                  class={style['log-detail-date']}
                  on-click={() => {
                    this.model = true;
                  }}>
                  日期：{this.operationDate}
                </div>
                <div class={style['log-detail-content']}>
                  {this.init && (
                    <div style={{ 'text-align': 'center', 'margin-top': '30px' }}>
                      <van-loading type='spinner' />
                    </div>
                  )}
                  {!this.init && Array.isArray(this.operationLogMessages) && !this.operationLogMessages.length && (
                    <van-empty description='当天日志记录为空！' />
                  )}
                  {Array.isArray(this.operationLogMessages) &&
                    this.operationLogMessages.map((item: ILogMessage) => (
                      <div class={style['log-detail-content-item']}>
                        <span class={style['log-detail-content-item-time']}>{item.time}</span>
                        <span
                          style={{
                            fontSize: '12px',
                            color: item.color
                              ? item.color === 'error'
                                ? '#ee0a24'
                                : item.color === 'success'
                                ? '#07c160'
                                : '#ff8917'
                              : '#666'
                          }}>
                          {item.value}
                        </span>
                      </div>
                    ))}
                </div>
              </div>
            </van-swipe-item>
          </van-swipe>
        </div>
        <van-calendar
          v-model={this.model}
          color='#1989fa'
          on-select={this.selectDate}
          min-date={this.minDate}
          max-date={new Date()}
        />
      </eap-layout>
    );
  }

  private selectDate(date: Date) {
    this.model = false;
    const d = Utils.formatDate(date);
    this.operationDate = d;
    this.getLogByDate(d);
  }

  private getLogByDate(date: string) {
    if (!this.room || !date) {
      return this.$message.error('当前房间信息不存在，请退出重试！');
    }
    this.$socket.client.emit('log', { room_id: this.room.id, date }, (data: ILogInfoResp) => {
      if (data.result) {
        this.operationLogMessages = data.data || [];
        this.$message.success(data.message);
      } else {
        this.$message.error(data.message);
      }
    });
  }
}
